org.eclipse.jdt.core.dom.CompilationUnit Java Examples

The following examples show how to use org.eclipse.jdt.core.dom.CompilationUnit. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ReturnTypeSubProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public static void addMethodRetunsVoidProposals(IInvocationContext context, IProblemLocation problem, Collection<ICommandAccess> 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);
	}
}
 
Example #2
Source File: UnresolvedElementsSubProcessor.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
private static String getExpressionBaseName(Expression expr) {
	IBinding argBinding= Bindings.resolveExpressionBinding(expr, true);
	if (argBinding instanceof IVariableBinding) {
		IJavaProject project= null;
		ASTNode root= expr.getRoot();
		if (root instanceof CompilationUnit) {
			ITypeRoot typeRoot= ((CompilationUnit) root).getTypeRoot();
			if (typeRoot != null) {
				project= typeRoot.getJavaProject();
			}
		}
		return StubUtility.getBaseName((IVariableBinding)argBinding, project);
	}
	if (expr instanceof SimpleName) {
		return ((SimpleName) expr).getIdentifier();
	}
	return null;
}
 
Example #3
Source File: SarlClassPathDetector.java    From sarl with Apache License 2.0 6 votes vote down vote up
/** Visit the given Java compilation unit.
 *
 * @param jfile the compilation unit.
 */
protected void visitJavaCompilationUnit(IFile jfile) {
	final ICompilationUnit cu = JavaCore.createCompilationUnitFrom(jfile);
	if (cu != null) {
		final ASTParser parser = ASTParser.newParser(IASTSharedValues.SHARED_AST_LEVEL);
		parser.setSource(cu);
		parser.setFocalPosition(0);
		final CompilationUnit root = (CompilationUnit) parser.createAST(null);
		final PackageDeclaration packDecl = root.getPackage();

		final IPath packPath = jfile.getParent().getFullPath();
		final String cuName = jfile.getName();
		if (packDecl == null) {
			addToMap(this.sourceFolders, packPath, new Path(cuName));
		} else {
			final IPath relPath = new Path(packDecl.getName().getFullyQualifiedName().replace('.', '/'));
			final IPath folderPath = getFolderPath(packPath, relPath);
			if (folderPath != null) {
				addToMap(this.sourceFolders, folderPath, relPath.append(cuName));
			}
		}
	}
}
 
Example #4
Source File: NewTypeWizardPage.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Uses the New Java file template from the code template page to generate a
 * compilation unit with the given type content.
 * 
 * @param cu The new created compilation unit
 * @param typeContent The content of the type, including signature and type
 * body.
 * @param lineDelimiter The line delimiter to be used.
 * @return String Returns the result of evaluating the new file template
 * with the given type content.
 * @throws CoreException when fetching the file comment fails or fetching the content for the
 *             new compilation unit fails
 * @since 2.1
 */
protected String constructCUContent(ICompilationUnit cu, String typeContent, String lineDelimiter) throws CoreException {
	String fileComment= getFileComment(cu, lineDelimiter);
	String typeComment= getTypeComment(cu, lineDelimiter);
	IPackageFragment pack= (IPackageFragment) cu.getParent();
	String content= CodeGeneration.getCompilationUnitContent(cu, fileComment, typeComment, typeContent, lineDelimiter);
	if (content != null) {
		ASTParser parser= ASTParser.newParser(ASTProvider.SHARED_AST_LEVEL);
		parser.setProject(cu.getJavaProject());
		parser.setSource(content.toCharArray());
		CompilationUnit unit= (CompilationUnit) parser.createAST(null);
		if ((pack.isDefaultPackage() || unit.getPackage() != null) && !unit.types().isEmpty()) {
			return content;
		}
	}
	StringBuffer buf= new StringBuffer();
	if (!pack.isDefaultPackage()) {
		buf.append("package ").append(pack.getElementName()).append(';'); //$NON-NLS-1$
	}
	buf.append(lineDelimiter).append(lineDelimiter);
	if (typeComment != null) {
		buf.append(typeComment).append(lineDelimiter);
	}
	buf.append(typeContent);
	return buf.toString();
}
 
Example #5
Source File: ConstructorReferenceFinder.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private SearchResultGroup[] removeUnrealReferences(SearchResultGroup[] groups) {
	List<SearchResultGroup> result= new ArrayList<SearchResultGroup>(groups.length);
	for (int i= 0; i < groups.length; i++) {
		SearchResultGroup group= groups[i];
		ICompilationUnit cu= group.getCompilationUnit();
		if (cu == null)
			continue;
		CompilationUnit cuNode= new RefactoringASTParser(ASTProvider.SHARED_AST_LEVEL).parse(cu, false);
		SearchMatch[] allSearchResults= group.getSearchResults();
		List<SearchMatch> realConstructorReferences= new ArrayList<SearchMatch>(Arrays.asList(allSearchResults));
		for (int j= 0; j < allSearchResults.length; j++) {
			SearchMatch searchResult= allSearchResults[j];
			if (! isRealConstructorReferenceNode(ASTNodeSearchUtil.getAstNode(searchResult, cuNode)))
				realConstructorReferences.remove(searchResult);
		}
		if (! realConstructorReferences.isEmpty())
			result.add(new SearchResultGroup(group.getResource(), realConstructorReferences.toArray(new SearchMatch[realConstructorReferences.size()])));
	}
	return result.toArray(new SearchResultGroup[result.size()]);
}
 
Example #6
Source File: CodeStyleFix.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public static CompilationUnitRewriteOperationsFix[] createNonStaticAccessFixes(CompilationUnit compilationUnit, IProblemLocation problem) {
	if (!isNonStaticAccess(problem))
		return null;

	ToStaticAccessOperation operations[]= createToStaticAccessOperations(compilationUnit, new HashMap<ASTNode, Block>(), problem, false);
	if (operations == null)
		return null;

	String label1= Messages.format(FixMessages.CodeStyleFix_ChangeAccessToStatic_description, operations[0].getAccessorName());
	CompilationUnitRewriteOperationsFix fix1= new CompilationUnitRewriteOperationsFix(label1, compilationUnit, operations[0]);

	if (operations.length > 1) {
		String label2= Messages.format(FixMessages.CodeStyleFix_ChangeAccessToStaticUsingInstanceType_description, operations[1].getAccessorName());
		CompilationUnitRewriteOperationsFix fix2= new CompilationUnitRewriteOperationsFix(label2, compilationUnit, operations[1]);
		return new CompilationUnitRewriteOperationsFix[] {fix1, fix2};
	}
	return new CompilationUnitRewriteOperationsFix[] {fix1};
}
 
Example #7
Source File: IntroduceParameterObjectProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
@Override
protected boolean shouldReport(IProblem problem, CompilationUnit cu) {
	if (!super.shouldReport(problem, cu))
		return false;
	ASTNode node= ASTNodeSearchUtil.getAstNode(cu, problem.getSourceStart(), problem.getSourceEnd() - problem.getSourceStart() + 1);
	if (node instanceof Type) {
		Type type= (Type) node;
		if (problem.getID() == IProblem.UndefinedType && getClassName().equals(ASTNodes.getTypeName(type))) {
			return false;
		}
	}
	if (node instanceof Name) {
		Name name= (Name) node;
		if (problem.getID() == IProblem.ImportNotFound && getPackage().indexOf(name.getFullyQualifiedName()) != -1)
			return false;
		if (problem.getID() == IProblem.MissingTypeInMethod) {
			StructuralPropertyDescriptor locationInParent= name.getLocationInParent();
			String[] arguments= problem.getArguments();
			if ((locationInParent == MethodInvocation.NAME_PROPERTY || locationInParent == SuperMethodInvocation.NAME_PROPERTY)
					&& arguments.length > 3
					&& arguments[3].endsWith(getClassName()))
				return false;
		}
	}
	return true;
}
 
Example #8
Source File: AddArgumentCorrectionProposal.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
private Expression evaluateArgumentExpressions(AST ast, ITypeBinding requiredType, String key) {
	CompilationUnit root= (CompilationUnit) fCallerNode.getRoot();

	int offset= fCallerNode.getStartPosition();
	Expression best= null;
	ITypeBinding bestType= null;

	ScopeAnalyzer analyzer= new ScopeAnalyzer(root);
	IBinding[] bindings= analyzer.getDeclarationsInScope(offset, ScopeAnalyzer.VARIABLES);
	for (int i= 0; i < bindings.length; i++) {
		IVariableBinding curr= (IVariableBinding) bindings[i];
		ITypeBinding type= curr.getType();
		if (type != null && canAssign(type, requiredType) && testModifier(curr)) {
			if (best == null || isMoreSpecific(bestType, type)) {
				best= ast.newSimpleName(curr.getName());
				bestType= type;
			}
		}
	}
	Expression defaultExpression= ASTNodeFactory.newDefaultExpression(ast, requiredType);
	if (best == null) {
		best= defaultExpression;
	}
	return best;
}
 
Example #9
Source File: ImportRewriteAnalyzer.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private IRegion evaluateReplaceRange(CompilationUnit root) {
	List imports= root.imports();
	if (!imports.isEmpty()) {
		ImportDeclaration first= (ImportDeclaration) imports.get(0);
		ImportDeclaration last= (ImportDeclaration) imports.get(imports.size() - 1);

		int startPos= first.getStartPosition(); // no extended range for first: bug 121428
		int endPos= root.getExtendedStartPosition(last) + root.getExtendedLength(last);
		int endLine= root.getLineNumber(endPos);
		if (endLine > 0) {
			int nextLinePos= root.getPosition(endLine + 1, 0);
			if (nextLinePos >= 0) {
				int firstTypePos= getFirstTypeBeginPos(root);
				if (firstTypePos != -1 && firstTypePos < nextLinePos) {
					endPos= firstTypePos;
				} else {
					endPos= nextLinePos;
				}
			}
		}
		return new Region(startPos, endPos - startPos);
	} else {
		int start= getPackageStatementEndPos(root);
		return new Region(start, 0);
	}
}
 
Example #10
Source File: Java7BaseTest.java    From compiler with Apache License 2.0 6 votes vote down vote up
protected static void dumpJava(final String content) {
	final ASTParser parser = ASTParser.newParser(astLevel);
	parser.setKind(ASTParser.K_COMPILATION_UNIT);
	parser.setSource(content.toCharArray());

	final Map<?, ?> options = JavaCore.getOptions();
	JavaCore.setComplianceOptions(javaVersion, options);
	parser.setCompilerOptions(options);

	final CompilationUnit cu = (CompilationUnit) parser.createAST(null);

	try {
		final UglyMathCommentsExtractor cex = new UglyMathCommentsExtractor(cu, content);
		final ASTDumper dumper = new ASTDumper(cex);
		dumper.dump(cu);
		cex.close();
	} catch (final Exception e) {}
}
 
Example #11
Source File: JavaEditor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
protected void installOccurrencesFinder(boolean forceUpdate) {
	fMarkOccurrenceAnnotations= true;

	fPostSelectionListenerWithAST= new ISelectionListenerWithAST() {
		public void selectionChanged(IEditorPart part, ITextSelection selection, CompilationUnit astRoot) {
			updateOccurrenceAnnotations(selection, astRoot);
		}
	};
	SelectionListenerWithASTManager.getDefault().addListener(this, fPostSelectionListenerWithAST);
	if (forceUpdate && getSelectionProvider() != null) {
		fForcedMarkOccurrencesSelection= getSelectionProvider().getSelection();
		ITypeRoot inputJavaElement= getInputJavaElement();
		if (inputJavaElement != null)
			updateOccurrenceAnnotations((ITextSelection)fForcedMarkOccurrencesSelection, SharedASTProvider.getAST(inputJavaElement, SharedASTProvider.WAIT_NO, getProgressMonitor()));
	}

	if (fOccurrencesFinderJobCanceler == null) {
		fOccurrencesFinderJobCanceler= new OccurrencesFinderJobCanceler();
		fOccurrencesFinderJobCanceler.install();
	}
}
 
Example #12
Source File: NLSStringHover.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public IRegion getHoverRegion(ITextViewer textViewer, int offset) {
	if (!(getEditor() instanceof JavaEditor))
		return null;

	ITypeRoot je= getEditorInputJavaElement();
	if (je == null)
		return null;

	// Never wait for an AST in UI thread.
	CompilationUnit ast= SharedASTProvider.getAST(je, SharedASTProvider.WAIT_NO, null);
	if (ast == null)
		return null;

	ASTNode node= NodeFinder.perform(ast, offset, 1);
	if (node instanceof StringLiteral) {
		StringLiteral stringLiteral= (StringLiteral)node;
		return new Region(stringLiteral.getStartPosition(), stringLiteral.getLength());
	} else if (node instanceof SimpleName) {
		SimpleName simpleName= (SimpleName)node;
		return new Region(simpleName.getStartPosition(), simpleName.getLength());
	}

	return null;
}
 
Example #13
Source File: UMLModelASTReader.java    From RefactoringMiner with MIT License 6 votes vote down vote up
private UMLModelASTReader(File rootFolder, ASTParser parser, List<String> javaFiles, Set<String> repositoryDirectories) {
	this.umlModel = new UMLModel(repositoryDirectories);
	this.projectRoot = rootFolder.getPath();
	this.parser = parser;
	final String[] emptyArray = new String[0];
	
	String[] filesArray = new String[javaFiles.size()];
	for (int i = 0; i < filesArray.length; i++) {
		filesArray[i] = rootFolder + File.separator + javaFiles.get(i).replaceAll("/", systemFileSeparator);
	}

	FileASTRequestor fileASTRequestor = new FileASTRequestor() { 
		@Override
		public void acceptAST(String sourceFilePath, CompilationUnit ast) {
			String relativePath = sourceFilePath.substring(projectRoot.length() + 1).replaceAll(systemFileSeparator, "/");
			processCompilationUnit(relativePath, ast);
		}
	};
	this.parser.createASTs((String[]) filesArray, null, emptyArray, fileASTRequestor, null);
}
 
Example #14
Source File: JavaMethodClassCounter.java    From api-mining with GNU General Public License v3.0 6 votes vote down vote up
public static void countMethodsClasses(final File projectDir)
		throws IOException {

	System.out.println("\n===== Project " + projectDir);
	final MethodClassCountVisitor mccv = new MethodClassCountVisitor();
	final JavaASTExtractor astExtractor = new JavaASTExtractor(false);

	final List<File> files = (List<File>) FileUtils.listFiles(projectDir,
			new String[] { "java" }, true);

	int count = 0;
	for (final File file : files) {

		final CompilationUnit cu = astExtractor.getAST(file);
		cu.accept(mccv);

		if (count % 1000 == 0)
			System.out.println("At file " + count + " of " + files.size());
		count++;
	}

	System.out.println("Project " + projectDir);
	System.out.println("No. *.java files " + files.size());
	System.out.println("No. Methods: " + mccv.noMethods);
	System.out.println("No. Classes: " + mccv.noClasses);
}
 
Example #15
Source File: OverrideIndicatorLabelDecorator.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private int findInHierarchyWithAST(CompilationUnit astRoot, IMethod method) throws JavaModelException {
	ASTNode node= NodeFinder.perform(astRoot, method.getNameRange());
	if (node instanceof SimpleName && node.getParent() instanceof MethodDeclaration) {
		IMethodBinding binding= ((MethodDeclaration) node.getParent()).resolveBinding();
		if (binding != null) {
			IMethodBinding defining= Bindings.findOverriddenMethod(binding, true);
			if (defining != null) {
				if (JdtFlags.isAbstract(defining)) {
					return JavaElementImageDescriptor.IMPLEMENTS;
				} else {
					return JavaElementImageDescriptor.OVERRIDES;
				}
			}
			return 0;
		}
	}
	return -1;
}
 
Example #16
Source File: AddUnimplementedConstructorsOperation.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Creates a new add unimplemented constructors operation.
 *
 * @param astRoot the compilation unit AST node
 * @param type the type to add the methods to
 * @param constructorsToImplement the method binding keys to implement
 * @param insertPos the insertion point, or <code>-1</code>
 * @param imports <code>true</code> if the import edits should be applied, <code>false</code> otherwise
 * @param apply <code>true</code> if the resulting edit should be applied, <code>false</code> otherwise
 * @param save <code>true</code> if the changed compilation unit should be saved, <code>false</code> otherwise
 */
public AddUnimplementedConstructorsOperation(CompilationUnit astRoot, ITypeBinding type, IMethodBinding[] constructorsToImplement, int insertPos, final boolean imports, final boolean apply, final boolean save) {
	if (astRoot == null || !(astRoot.getJavaElement() instanceof ICompilationUnit)) {
		throw new IllegalArgumentException("AST must not be null and has to be created from a ICompilationUnit"); //$NON-NLS-1$
	}
	if (type == null) {
		throw new IllegalArgumentException("The type must not be null"); //$NON-NLS-1$
	}
	ASTNode node= astRoot.findDeclaringNode(type);
	if (!(node instanceof AnonymousClassDeclaration || node instanceof AbstractTypeDeclaration)) {
		throw new IllegalArgumentException("type has to map to a type declaration in the AST"); //$NON-NLS-1$
	}

	fType= type;
	fInsertPos= insertPos;
	fASTRoot= astRoot;
	fConstructorsToImplement= constructorsToImplement;
	fSave= save;
	fApply= apply;
	fImports= imports;

	fCreateComments= StubUtility.doAddComments(astRoot.getJavaElement().getJavaProject());
	fVisibility= Modifier.PUBLIC;
	fOmitSuper= false;
}
 
Example #17
Source File: GenerateConstructorsHandler.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private static IMethodBinding[] getVisibleConstructors(CompilationUnit astRoot, ITypeBinding typeBinding) {
	if (typeBinding.isEnum()) {
		return new IMethodBinding[] { getObjectConstructor(astRoot.getAST()) };
	} else {
		return StubUtility2Core.getVisibleConstructors(typeBinding, false, true);
	}
}
 
Example #18
Source File: TypeParametersFix.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public static ICleanUpFix createCleanUp(CompilationUnit compilationUnit, boolean insertInferredTypeArguments, boolean removeRedundantTypeArguments) {

		IProblem[] problems= compilationUnit.getProblems();
		IProblemLocation[] locations= new IProblemLocation[problems.length];
		for (int i= 0; i < problems.length; i++) {
			locations[i]= new ProblemLocation(problems[i]);
		}

		return createCleanUp(compilationUnit, locations,
				insertInferredTypeArguments,
				removeRedundantTypeArguments);
	}
 
Example #19
Source File: ObjectCreation.java    From RefactoringMiner with MIT License 5 votes vote down vote up
public ObjectCreation(CompilationUnit cu, String filePath, ArrayCreation creation) {
	this.locationInfo = new LocationInfo(cu, filePath, creation, CodeElementType.ARRAY_CREATION);
	this.isArray = true;
	this.type = UMLType.extractTypeObject(cu, filePath, creation.getType(), 0);
	this.typeArguments = creation.dimensions().size();
	this.arguments = new ArrayList<String>();
	List<Expression> args = creation.dimensions();
	for(Expression argument : args) {
		this.arguments.add(argument.toString());
	}
	if(creation.getInitializer() != null) {
		this.anonymousClassDeclaration = creation.getInitializer().toString();
	}
}
 
Example #20
Source File: NodeUtils.java    From SimFix with GNU General Public License v2.0 5 votes vote down vote up
private static String getFullClazzName(MethodDeclaration node) {
	String clazz = "";
	// filter those methods that defined in anonymous classes
	ASTNode parent = node.getParent();
	while (parent != null) {
		if (parent instanceof ClassInstanceCreation) {
			return null;
		} else if(parent instanceof TypeDeclaration){
			clazz = ((TypeDeclaration) parent).getName().getFullyQualifiedName();
			break;
		} else if(parent instanceof EnumDeclaration){
			clazz = ((EnumDeclaration) parent).getName().getFullyQualifiedName();
			break;
		}
		parent = parent.getParent();
	}
	if(parent != null){
		while(parent != null){
			if(parent instanceof CompilationUnit){
				String packageName = ((CompilationUnit) parent).getPackage().getName().getFullyQualifiedName();
				clazz = packageName + "." + clazz;
				return clazz;
			}
			parent = parent.getParent();
		}
	}
	return null;
}
 
Example #21
Source File: NewAnnotationMemberProposal.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
@Override
protected ASTRewrite getRewrite() throws CoreException {
	CompilationUnit astRoot= ASTResolving.findParentCompilationUnit(fInvocationNode);
	ASTNode typeDecl= astRoot.findDeclaringNode(fSenderBinding);
	ASTNode newTypeDecl= null;
	if (typeDecl != null) {
		newTypeDecl= typeDecl;
	} else {
		astRoot= ASTResolving.createQuickFixAST(getCompilationUnit(), null);
		newTypeDecl= astRoot.findDeclaringNode(fSenderBinding.getKey());
	}
	createImportRewrite(astRoot);

	if (newTypeDecl instanceof AnnotationTypeDeclaration) {
		AnnotationTypeDeclaration newAnnotationTypeDecl= (AnnotationTypeDeclaration) newTypeDecl;

		ASTRewrite rewrite= ASTRewrite.create(astRoot.getAST());

		AnnotationTypeMemberDeclaration newStub= getStub(rewrite, newAnnotationTypeDecl);

		List<BodyDeclaration> members= newAnnotationTypeDecl.bodyDeclarations();
		int insertIndex= members.size();

		ListRewrite listRewriter= rewrite.getListRewrite(newAnnotationTypeDecl, AnnotationTypeDeclaration.BODY_DECLARATIONS_PROPERTY);
		listRewriter.insertAt(newStub, insertIndex, null);

		return rewrite;
	}
	return null;
}
 
Example #22
Source File: UnresolvedElementsSubProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private static void addNewFieldProposals(ICompilationUnit cu, CompilationUnit astRoot, ITypeBinding binding, ITypeBinding declaringTypeBinding, SimpleName simpleName, boolean isWriteAccess, Collection<ICommandAccess> proposals) throws JavaModelException {
	// new variables
	ICompilationUnit targetCU;
	ITypeBinding senderDeclBinding;
	if (binding != null) {
		senderDeclBinding= binding.getTypeDeclaration();
		targetCU= ASTResolving.findCompilationUnitForBinding(cu, astRoot, senderDeclBinding);
	} else { // binding is null for accesses without qualifier
		senderDeclBinding= declaringTypeBinding;
		targetCU= cu;
	}

	if (!senderDeclBinding.isFromSource() || targetCU == null) {
		return;
	}

	boolean mustBeConst= ASTResolving.isInsideModifiers(simpleName);

	addNewFieldForType(targetCU, binding, senderDeclBinding, simpleName, isWriteAccess, mustBeConst, proposals);

	if (binding == null && senderDeclBinding.isNested()) {
		ASTNode anonymDecl= astRoot.findDeclaringNode(senderDeclBinding);
		if (anonymDecl != null) {
			ITypeBinding bind= Bindings.getBindingOfParentType(anonymDecl.getParent());
			if (!bind.isAnonymous()) {
				addNewFieldForType(targetCU, bind, bind, simpleName, isWriteAccess, mustBeConst, proposals);
			}
		}
	}
}
 
Example #23
Source File: JavadocContentAccess2.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private static Javadoc getPackageJavadocNode(IJavaElement element, String cuSource) {
	CompilationUnit cu= createAST(element, cuSource);
	if (cu != null) {
		PackageDeclaration packDecl= cu.getPackage();
		if (packDecl != null) {
			return packDecl.getJavadoc();
		}
	}
	return null;
}
 
Example #24
Source File: JavaTypeHierarchyExtractor.java    From api-mining with GNU General Public License v3.0 5 votes vote down vote up
private Collection<Pair<String, String>> getParentTypeRelationshipsFrom(
		final File file) {
	final JavaASTExtractor ex = new JavaASTExtractor(true);
	try {
		final CompilationUnit ast = ex.getAST(file);
		final HierarchyExtractor hEx = new HierarchyExtractor();
		ast.accept(hEx);
		return hEx.parentChildRelationships;
	} catch (final IOException e) {
		LOGGER.warning(ExceptionUtils.getFullStackTrace(e));
	}
	return Collections.emptySet();
}
 
Example #25
Source File: MethodsInClass.java    From api-mining with GNU General Public License v3.0 5 votes vote down vote up
@Override
public boolean visit(final CompilationUnit node) {
	if (node.getPackage() != null) {
		currentPackageName = node.getPackage().getName()
				.getFullyQualifiedName();
	}
	return super.visit(node);
}
 
Example #26
Source File: UiBinderJavaValidator.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 5 votes vote down vote up
public UiBinderJavaValidator(CompilationUnit cu,
    UiBinderSubtypeToOwnerIndex uiBinderToOwner,
    UiBinderSubtypeToUiXmlIndex ownerToUiXml,
    UiXmlReferencedFieldIndex uiXmlFieldRefs,
    ReferenceManager referenceManager) {
  this.cu = cu;
  this.javaProject = JavaASTUtils.getCompilationUnit(cu).getJavaProject();
  this.uiBinderToOwner = uiBinderToOwner;
  this.ownerToUiXml = ownerToUiXml;
  this.uiXmlFieldRefs = uiXmlFieldRefs;
  this.referenceManager = referenceManager;
}
 
Example #27
Source File: RenameTypeProcessor.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private void checkCUCompleteConditions(final RefactoringStatus status, CompilationUnit currentResolvedCU, ICompilationUnit currentCU, List<RefactoringProcessor> processors) throws CoreException {

		// check local variable conditions
		List<RefactoringProcessor> locals = getProcessorsOfType(processors, RenameLocalVariableProcessor.class);
		if (!locals.isEmpty()) {
			RenameAnalyzeUtil.LocalAnalyzePackage[] analyzePackages = new RenameAnalyzeUtil.LocalAnalyzePackage[locals.size()];
			TextChangeManager manager = new TextChangeManager();
			int current = 0;
			TextChange textChange = manager.get(currentCU);
			textChange.setKeepPreviewEdits(true);
			for (Iterator<RefactoringProcessor> iterator = locals.iterator(); iterator.hasNext();) {
				RenameLocalVariableProcessor localProcessor = (RenameLocalVariableProcessor) iterator.next();
				RenameAnalyzeUtil.LocalAnalyzePackage analyzePackage = localProcessor.getLocalAnalyzePackage();
				analyzePackages[current] = analyzePackage;
				for (int i = 0; i < analyzePackage.fOccurenceEdits.length; i++) {
					TextChangeCompatibility.addTextEdit(textChange, "", analyzePackage.fOccurenceEdits[i], GroupCategorySet.NONE); //$NON-NLS-1$
				}
				current++;
			}
			status.merge(RenameAnalyzeUtil.analyzeLocalRenames(analyzePackages, textChange, currentResolvedCU, false));
		}

		/*
		 * There is room for performance improvement here: One could move
		 * shadowing analyzes out of the field and method processors and perform
		 * it here, thus saving on working copy creation. Drawback is increased
		 * heap consumption.
		 */
	}
 
Example #28
Source File: JavaDebugElementCodeMiningASTVisitor.java    From jdt-codemining with Eclipse Public License 1.0 5 votes vote down vote up
public JavaDebugElementCodeMiningASTVisitor(IJavaStackFrame frame, CompilationUnit cu, ITextViewer viewer,
		List<ICodeMining> minings, AbstractDebugVariableCodeMiningProvider provider) {
	this.cu = cu;
	this.minings = minings;
	this.provider = provider;
	this.viewer = viewer;
	this.fFrame = frame;
}
 
Example #29
Source File: MethodEvolution.java    From JDeodorant with MIT License 5 votes vote down vote up
private List<String> getStringRepresentation(IMethod method, ProjectVersion version) {
	List<String> stringRepresentation = null;
	if(method != null) {
		ICompilationUnit iCompilationUnit = method.getCompilationUnit();
		ASTParser parser = ASTParser.newParser(ASTReader.JLS);
		parser.setKind(ASTParser.K_COMPILATION_UNIT);
		parser.setSource(iCompilationUnit);
		parser.setResolveBindings(true);
		CompilationUnit compilationUnit = (CompilationUnit)parser.createAST(null);
		IType declaringType = method.getDeclaringType();
		TypeDeclaration typeDeclaration = (TypeDeclaration)compilationUnit.findDeclaringNode(declaringType.getKey());
		MethodDeclaration matchingMethodDeclaration = null;
		for(MethodDeclaration methodDeclaration : typeDeclaration.getMethods()) {
			IMethod resolvedMethod = (IMethod)methodDeclaration.resolveBinding().getJavaElement();
			if(resolvedMethod.isSimilar(method)) {
				matchingMethodDeclaration = methodDeclaration;
				break;
			}
		}
		if(matchingMethodDeclaration != null && matchingMethodDeclaration.getBody() != null) {
			methodCodeMap.put(version, matchingMethodDeclaration.toString());
			ASTInformationGenerator.setCurrentITypeRoot(iCompilationUnit);
			MethodBodyObject methodBody = new MethodBodyObject(matchingMethodDeclaration.getBody());
			stringRepresentation = methodBody.stringRepresentation();
		}
	}
	return stringRepresentation;
}
 
Example #30
Source File: SM_TypeTest.java    From DesigniteJava with Apache License 2.0 5 votes vote down vote up
@Test
public void SM_Type_check_isInterface() {
	CompilationUnit unit = project.createCU(getTestingPath() + File.separator +"test_package"+File.separator +"Interface.java");
	List<TypeDeclaration> typeList = unit.types();

	SM_Type type = null;
	for (TypeDeclaration typeDecl : typeList)
		type = new SM_Type(typeDecl, unit, new SM_Package("Test", project, null), null);
	assertTrue(type.isInterface());		
}