Java Code Examples for org.eclipse.jdt.core.dom.ASTParser#newParser()

The following examples show how to use org.eclipse.jdt.core.dom.ASTParser#newParser() . 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: JdtTypeProviderTest.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
@SuppressWarnings("deprecation")
private boolean isParameterNamesAvailable() throws Exception {
	ASTParser parser = ASTParser.newParser(AST.JLS3);
	parser.setIgnoreMethodBodies(true);
	IJavaProject javaProject = projectProvider.getJavaProject(resourceSet);
	parser.setProject(javaProject);
	IType type = javaProject.findType("org.eclipse.xtext.common.types.testSetups.TestEnum");
	IBinding[] bindings = parser.createBindings(new IJavaElement[] { type }, null);
	ITypeBinding typeBinding = (ITypeBinding) bindings[0];
	IMethodBinding[] methods = typeBinding.getDeclaredMethods();
	for(IMethodBinding method: methods) {
		if (method.isConstructor()) {
			IMethod element = (IMethod) method.getJavaElement();
			if (element.exists()) {
				String[] parameterNames = element.getParameterNames();
				if (parameterNames.length == 1 && parameterNames[0].equals("string")) {
					return true;
				}
			} else {
				return false;
			}
		}
	}
	return false;
}
 
Example 2
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 3
Source File: StubUtility.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private static String[] getParameterTypeNamesForSeeTag(IMethod overridden) {
	try {
		ASTParser parser= ASTParser.newParser(ASTProvider.SHARED_AST_LEVEL);
		parser.setProject(overridden.getJavaProject());
		IBinding[] bindings= parser.createBindings(new IJavaElement[] { overridden }, null);
		if (bindings.length == 1 && bindings[0] instanceof IMethodBinding) {
			return getParameterTypeNamesForSeeTag((IMethodBinding)bindings[0]);
		}
	} catch (IllegalStateException e) {
		// method does not exist
	}
	// fall back code. Not good for generic methods!
	String[] paramTypes= overridden.getParameterTypes();
	String[] paramTypeNames= new String[paramTypes.length];
	for (int i= 0; i < paramTypes.length; i++) {
		paramTypeNames[i]= Signature.toString(Signature.getTypeErasure(paramTypes[i]));
	}
	return paramTypeNames;
}
 
Example 4
Source File: JavaStatementPostfixContext.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private void initDomAST() {
		if (isReadOnly())
			return;
		
		ASTParser parser= ASTParser.newParser(AST.JLS8);
		parser.setSource(getCompilationUnit());
		parser.setResolveBindings(true);
		org.eclipse.jdt.core.dom.ASTNode domAst = parser.createAST(new NullProgressMonitor());
		
//		org.eclipse.jdt.core.dom.AST ast = domAst.getAST();
		
		NodeFinder nf = new NodeFinder(domAst, getCompletionOffset(), 1);
		org.eclipse.jdt.core.dom.ASTNode cv = nf.getCoveringNode();
		
		bodyDeclaration = ASTResolving.findParentBodyDeclaration(cv);
		parentDeclaration = ASTResolving.findParentType(cv);
		domInitialized = true;
	}
 
Example 5
Source File: ClassPathDetector.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private void visitCompilationUnit(IFile file) {
	ICompilationUnit cu= JavaCore.createCompilationUnitFrom(file);
	if (cu != null) {
		ASTParser parser= ASTParser.newParser(ASTProvider.SHARED_AST_LEVEL);
		parser.setSource(cu);
		parser.setFocalPosition(0);
		CompilationUnit root= (CompilationUnit)parser.createAST(null);
		PackageDeclaration packDecl= root.getPackage();
		
		IPath packPath= file.getParent().getFullPath();
		String cuName= file.getName();
		if (packDecl == null) {
			addToMap(fSourceFolders, packPath, new Path(cuName));
		} else {
			IPath relPath= new Path(packDecl.getName().getFullyQualifiedName().replace('.', '/'));
			IPath folderPath= getFolderPath(packPath, relPath);
			if (folderPath != null) {
				addToMap(fSourceFolders, folderPath, relPath.append(cuName));
			}
		}
	}
}
 
Example 6
Source File: TypedSource.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private static String getFieldSource(IField field, SourceTuple tuple) throws CoreException {
	if (Flags.isEnum(field.getFlags())) {
		String source= field.getSource();
		if (source != null)
			return source;
	} else {
		if (tuple.node == null) {
			ASTParser parser= ASTParser.newParser(ASTProvider.SHARED_AST_LEVEL);
			parser.setSource(tuple.unit);
			tuple.node= (CompilationUnit) parser.createAST(null);
		}
		FieldDeclaration declaration= ASTNodeSearchUtil.getFieldDeclarationNode(field, tuple.node);
		if (declaration.fragments().size() == 1)
			return getSourceOfDeclararationNode(field, tuple.unit);
		VariableDeclarationFragment declarationFragment= ASTNodeSearchUtil.getFieldDeclarationFragmentNode(field, tuple.node);
		IBuffer buffer= tuple.unit.getBuffer();
		StringBuffer buff= new StringBuffer();
		buff.append(buffer.getText(declaration.getStartPosition(), ((ASTNode) declaration.fragments().get(0)).getStartPosition() - declaration.getStartPosition()));
		buff.append(buffer.getText(declarationFragment.getStartPosition(), declarationFragment.getLength()));
		buff.append(";"); //$NON-NLS-1$
		return buff.toString();
	}
	return ""; //$NON-NLS-1$
}
 
Example 7
Source File: JavaParser.java    From repositoryminer with Apache License 2.0 5 votes vote down vote up
@Override
public AST generate(String filename, String source, String[] srcFolders) {
	AST ast = new AST();
	ast.setFileName(filename);
	ast.setSource(source);

	ASTParser parser = ASTParser.newParser(org.eclipse.jdt.core.dom.AST.JLS10);
	parser.setResolveBindings(true);
	parser.setKind(ASTParser.K_COMPILATION_UNIT);
	parser.setBindingsRecovery(true);
	parser.setCompilerOptions(JavaCore.getOptions());
	parser.setUnitName(filename);
	parser.setSource(source.toCharArray());

	parser.setEnvironment(null, srcFolders, null, true);
	
	CompilationUnit cu = (CompilationUnit) parser.createAST(null);

	FileVisitor visitor = new FileVisitor();
	cu.accept(visitor);

	ast.setImports(visitor.getImports());
	ast.setPackageDeclaration(visitor.getPackageName());
	ast.setTypes(visitor.getTypes());
	ast.setLanguage(Language.JAVA);

	return ast;
}
 
Example 8
Source File: JsniParserTest.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 5 votes vote down vote up
public void testParseMethodDeclaration() {
  // Have JDT parse the compilation unit
  ASTParser parser = ASTParser.newParser(AST.JLS3);
  parser.setProject(getTestProject());
  parser.setResolveBindings(false);
  parser.setSource(testClass.getCompilationUnit());
  CompilationUnit root = (CompilationUnit) parser.createAST(null);

  // Find the JSNI method and parse it
  TypeDeclaration typeDecl = (TypeDeclaration) root.types().get(0);
  MethodDeclaration jsniMethod = typeDecl.getMethods()[0];
  JavaValidationResult result = JsniParser.parse(jsniMethod);

  // Verify the Java refs
  List<JsniJavaRef> refs = result.getJavaRefs();
  assertEquals(3, refs.size());
  assertTrue(refs.contains(JsniJavaRef.parse("@com.hello.client.A$B::getNumber()")));
  assertTrue(refs.contains(JsniJavaRef.parse("@com.hello.client.JsniParserTest::getSum(II)")));
  assertTrue(refs.contains(JsniJavaRef.parse("@com.hello.client.JsniParserTest::counter")));

  // Verify the problems
  List<GWTJavaProblem> problems = result.getProblems();
  assertEquals(1, problems.size());
  GWTJavaProblem problem = problems.get(0);
  assertEquals(GWTProblemType.JSNI_JAVA_REF_UNRESOLVED_TYPE, problem.getProblemType());
  IRegion expectedProblemRegion = RegionConverter.convertWindowsRegion(184, 0, testClass.getContents());
  assertEquals(expectedProblemRegion.getOffset(), problem.getSourceStart());
}
 
Example 9
Source File: ASTNodeFactory.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public static ASTNode newStatement(AST ast, String content) {
	StringBuffer buffer= new StringBuffer(STATEMENT_HEADER);
	buffer.append(content);
	buffer.append(STATEMENT_FOOTER);
	ASTParser p= ASTParser.newParser(ast.apiLevel());
	p.setSource(buffer.toString().toCharArray());
	CompilationUnit root= (CompilationUnit) p.createAST(null);
	ASTNode result= ASTNode.copySubtree(ast, NodeFinder.perform(root, STATEMENT_HEADER.length(), content.length()));
	result.accept(new PositionClearer());
	return result;
}
 
Example 10
Source File: ReorgPolicyFactory.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private CompilationUnit createSourceCuNode() {
	Assert.isTrue(getSourceCu() != null || getSourceClassFile() != null);
	Assert.isTrue(getSourceCu() == null || getSourceClassFile() == null);
	ASTParser parser= ASTParser.newParser(IASTSharedValues.SHARED_AST_LEVEL);
	parser.setBindingsRecovery(true);
	parser.setResolveBindings(true);
	if (getSourceCu() != null) {
		parser.setSource(getSourceCu());
	} else {
		parser.setSource(getSourceClassFile());
	}
	return (CompilationUnit) parser.createAST(null);
}
 
Example 11
Source File: LazyGenericTypeProposal.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Returns the type binding of the expected type as it is contained in the
 * code completion context.
 *
 * @return the binding of the expected type
 */
private ITypeBinding getExpectedType() {
	char[][] chKeys= fInvocationContext.getCoreContext().getExpectedTypesKeys();
	if (chKeys == null || chKeys.length == 0)
		return null;

	String[] keys= new String[chKeys.length];
	for (int i= 0; i < keys.length; i++) {
		keys[i]= String.valueOf(chKeys[0]);
	}

	final ASTParser parser= ASTParser.newParser(ASTProvider.SHARED_AST_LEVEL);
	parser.setProject(fCompilationUnit.getJavaProject());
	parser.setResolveBindings(true);
	parser.setStatementsRecovery(true);

	final Map<String, IBinding> bindings= new HashMap<String, IBinding>();
	ASTRequestor requestor= new ASTRequestor() {
		@Override
		public void acceptBinding(String bindingKey, IBinding binding) {
			bindings.put(bindingKey, binding);
		}
	};
	parser.createASTs(new ICompilationUnit[0], keys, requestor, null);

	if (bindings.size() > 0)
		return (ITypeBinding) bindings.get(keys[0]);

	return null;
}
 
Example 12
Source File: JavaASTUtils.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 5 votes vote down vote up
public static ITypeBinding findTypeBinding(IType currentType) throws JavaModelException{
  final ASTParser parser = ASTParser.newParser(AST.JLS3);
  parser.setKind(ASTParser.K_COMPILATION_UNIT);
  parser.setSource(currentType.getCompilationUnit());
  parser.setResolveBindings(true);
  CompilationUnit unit = (CompilationUnit) parser.createAST(null);
  return ASTNodes.getTypeBinding(unit, currentType);
}
 
Example 13
Source File: TypeURIHelper.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
public URI getFullURI(IJavaElement javaElement) {
	@SuppressWarnings("all")
	ASTParser parser = ASTParser.newParser(AST.JLS3);
	parser.setProject(javaElement.getJavaProject());
	IBinding[] bindings = parser.createBindings(new IJavaElement[] { javaElement }, null);
	if (bindings[0] != null) {
		return getFullURI(bindings[0]);
	}
	return null;
}
 
Example 14
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 15
Source File: ReorgPolicyFactory.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private CompilationUnit createSourceCuNode() {
	Assert.isTrue(getSourceCu() != null || getSourceClassFile() != null);
	Assert.isTrue(getSourceCu() == null || getSourceClassFile() == null);
	ASTParser parser= ASTParser.newParser(ASTProvider.SHARED_AST_LEVEL);
	parser.setBindingsRecovery(true);
	parser.setResolveBindings(true);
	if (getSourceCu() != null)
		parser.setSource(getSourceCu());
	else
		parser.setSource(getSourceClassFile());
	return (CompilationUnit) parser.createAST(null);
}
 
Example 16
Source File: NewTypeWizardPage.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Hook method that gets called when the type name has changed. The method validates the
 * type name and returns the status of the validation.
 * <p>
 * Subclasses may extend this method to perform their own validation.
 * </p>
 *
 * @return the status of the validation
 */
protected IStatus typeNameChanged() {
	StatusInfo status= new StatusInfo();
	fCurrType= null;
	String typeNameWithParameters= getTypeName();
	// must not be empty
	if (typeNameWithParameters.length() == 0) {
		status.setError(NewWizardMessages.NewTypeWizardPage_error_EnterTypeName);
		return status;
	}

	String typeName= getTypeNameWithoutParameters();
	if (typeName.indexOf('.') != -1) {
		status.setError(NewWizardMessages.NewTypeWizardPage_error_QualifiedName);
		return status;
	}

	IJavaProject project= getJavaProject();
	IStatus val= validateJavaTypeName(typeName, project);
	if (val.getSeverity() == IStatus.ERROR) {
		status.setError(Messages.format(NewWizardMessages.NewTypeWizardPage_error_InvalidTypeName, val.getMessage()));
		return status;
	} else if (val.getSeverity() == IStatus.WARNING) {
		status.setWarning(Messages.format(NewWizardMessages.NewTypeWizardPage_warning_TypeNameDiscouraged, val.getMessage()));
		// continue checking
	}

	// must not exist
	if (!isEnclosingTypeSelected()) {
		IPackageFragment pack= getPackageFragment();
		if (pack != null) {
			ICompilationUnit cu= pack.getCompilationUnit(getCompilationUnitName(typeName));
			fCurrType= cu.getType(typeName);
			IResource resource= cu.getResource();

			if (resource.exists()) {
				status.setError(NewWizardMessages.NewTypeWizardPage_error_TypeNameExists);
				return status;
			}
			if (!ResourcesPlugin.getWorkspace().validateFiltered(resource).isOK()) {
				status.setError(NewWizardMessages.NewTypeWizardPage_error_TypeNameFiltered);
				return status;
			}
			URI location= resource.getLocationURI();
			if (location != null) {
				try {
					IFileStore store= EFS.getStore(location);
					if (store.fetchInfo().exists()) {
						status.setError(NewWizardMessages.NewTypeWizardPage_error_TypeNameExistsDifferentCase);
						return status;
					}
				} catch (CoreException e) {
					status.setError(Messages.format(
						NewWizardMessages.NewTypeWizardPage_error_uri_location_unkown,
						BasicElementLabels.getURLPart(Resources.getLocationString(resource))));
				}
			}
		}
	} else {
		IType type= getEnclosingType();
		if (type != null) {
			fCurrType= type.getType(typeName);
			if (fCurrType.exists()) {
				status.setError(NewWizardMessages.NewTypeWizardPage_error_TypeNameExists);
				return status;
			}
		}
	}

	if (!typeNameWithParameters.equals(typeName) && project != null) {
		if (!JavaModelUtil.is50OrHigher(project)) {
			status.setError(NewWizardMessages.NewTypeWizardPage_error_TypeParameters);
			return status;
		}
		String typeDeclaration= "class " + typeNameWithParameters + " {}"; //$NON-NLS-1$//$NON-NLS-2$
		ASTParser parser= ASTParser.newParser(ASTProvider.SHARED_AST_LEVEL);
		parser.setSource(typeDeclaration.toCharArray());
		parser.setProject(project);
		CompilationUnit compilationUnit= (CompilationUnit) parser.createAST(null);
		IProblem[] problems= compilationUnit.getProblems();
		if (problems.length > 0) {
			status.setError(Messages.format(NewWizardMessages.NewTypeWizardPage_error_InvalidTypeName, problems[0].getMessage()));
			return status;
		}
	}
	return status;
}
 
Example 17
Source File: CreateTypeMemberOperation.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
protected ASTNode generateElementAST(ASTRewrite rewriter, ICompilationUnit cu) throws JavaModelException {
	if (this.createdNode == null) {
		this.source = removeIndentAndNewLines(this.source, cu);
		ASTParser parser = ASTParser.newParser(AST.JLS8);
		parser.setSource(this.source.toCharArray());
		parser.setProject(getCompilationUnit().getJavaProject());
		parser.setKind(ASTParser.K_CLASS_BODY_DECLARATIONS);
		ASTNode node = parser.createAST(this.progressMonitor);
		String createdNodeSource;
		if (node.getNodeType() != ASTNode.TYPE_DECLARATION) {
			createdNodeSource = generateSyntaxIncorrectAST();
			if (this.createdNode == null)
				throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.INVALID_CONTENTS));
		} else {
			TypeDeclaration typeDeclaration = (TypeDeclaration) node;
			if ((typeDeclaration.getFlags() & ASTNode.MALFORMED) != 0) {
				createdNodeSource = generateSyntaxIncorrectAST();
				if (this.createdNode == null)
					throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.INVALID_CONTENTS));
			} else {
				List bodyDeclarations = typeDeclaration.bodyDeclarations();
				if (bodyDeclarations.size() == 0) {
					throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.INVALID_CONTENTS));
				}
				this.createdNode = (ASTNode) bodyDeclarations.iterator().next();
				createdNodeSource = this.source;
			}
		}
		if (this.alteredName != null) {
			SimpleName newName = this.createdNode.getAST().newSimpleName(this.alteredName);
			SimpleName oldName = rename(this.createdNode, newName);
			int nameStart = oldName.getStartPosition();
			int nameEnd = nameStart + oldName.getLength();
			StringBuffer newSource = new StringBuffer();
			if (this.source.equals(createdNodeSource)) {
				newSource.append(createdNodeSource.substring(0, nameStart));
				newSource.append(this.alteredName);
				newSource.append(createdNodeSource.substring(nameEnd));
			} else {
				// syntactically incorrect source
				int createdNodeStart = this.createdNode.getStartPosition();
				int createdNodeEnd = createdNodeStart + this.createdNode.getLength();
				newSource.append(createdNodeSource.substring(createdNodeStart, nameStart));
				newSource.append(this.alteredName);
				newSource.append(createdNodeSource.substring(nameEnd, createdNodeEnd));

			}
			this.source = newSource.toString();
		}
	}
	if (rewriter == null) return this.createdNode;
	// return a string place holder (instead of the created node) so has to not lose comments and formatting
	return rewriter.createStringPlaceholder(this.source, this.createdNode.getNodeType());
}
 
Example 18
Source File: JavaASTExtractor.java    From tassal with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
/**
 * Return an ASTNode given the content
 *
 * @param content
 * @return
 */
public final ASTNode getASTNode(final char[] content,
		final ParseType parseType) {
	final ASTParser parser = ASTParser.newParser(AST.JLS8);
	final int astKind;
	switch (parseType) {
	case CLASS_BODY:
	case METHOD:
		astKind = ASTParser.K_CLASS_BODY_DECLARATIONS;
		break;
	case COMPILATION_UNIT:
		astKind = ASTParser.K_COMPILATION_UNIT;
		break;
	case EXPRESSION:
		astKind = ASTParser.K_EXPRESSION;
		break;
	case STATEMENTS:
		astKind = ASTParser.K_STATEMENTS;
		break;
	default:
		astKind = ASTParser.K_COMPILATION_UNIT;
	}
	parser.setKind(astKind);

	final Map<String, String> options = new Hashtable<String, String>();
	options.put(JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM,
			JavaCore.VERSION_1_8);
	options.put(JavaCore.COMPILER_SOURCE, JavaCore.VERSION_1_8);
	if (useJavadocs) {
		options.put(JavaCore.COMPILER_DOC_COMMENT_SUPPORT, JavaCore.ENABLED);
	}
	parser.setCompilerOptions(options);
	parser.setSource(content); // set source
	parser.setResolveBindings(useBindings);
	parser.setBindingsRecovery(useBindings);

	parser.setStatementsRecovery(true);

	if (parseType != ParseType.METHOD) {
		return parser.createAST(null);
	} else {
		final ASTNode cu = parser.createAST(null);
		return getFirstMethodDeclaration(cu);
	}
}
 
Example 19
Source File: JavaASTExtractor.java    From api-mining with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Return an ASTNode given the content
 *
 * @param content
 * @return
 */
public final ASTNode getASTNode(final char[] content,
		final ParseType parseType) {
	final ASTParser parser = ASTParser.newParser(AST.JLS8);
	final int astKind;
	switch (parseType) {
	case CLASS_BODY:
	case METHOD:
		astKind = ASTParser.K_CLASS_BODY_DECLARATIONS;
		break;
	case COMPILATION_UNIT:
		astKind = ASTParser.K_COMPILATION_UNIT;
		break;
	case EXPRESSION:
		astKind = ASTParser.K_EXPRESSION;
		break;
	case STATEMENTS:
		astKind = ASTParser.K_STATEMENTS;
		break;
	default:
		astKind = ASTParser.K_COMPILATION_UNIT;
	}
	parser.setKind(astKind);

	final Map<String, String> options = new Hashtable<String, String>();
	options.put(JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM,
			JavaCore.VERSION_1_8);
	options.put(JavaCore.COMPILER_SOURCE, JavaCore.VERSION_1_8);
	if (useJavadocs) {
		options.put(JavaCore.COMPILER_DOC_COMMENT_SUPPORT, JavaCore.ENABLED);
	}
	parser.setCompilerOptions(options);
	parser.setSource(content); // set source
	parser.setResolveBindings(useBindings);
	parser.setBindingsRecovery(useBindings);

	parser.setStatementsRecovery(true);

	if (parseType != ParseType.METHOD) {
		return parser.createAST(null);
	} else {
		final ASTNode cu = parser.createAST(null);
		return getFirstMethodDeclaration(cu);
	}
}
 
Example 20
Source File: ASTBatchParser.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 3 votes vote down vote up
/**
 * Creates a new parser which can be used to create ASTs
 * for compilation units in <code>project</code>
 * <p>
 * Subclasses may override
 * </p>
 *
 * @param project the project for which ASTs are been generated
 * @return an AST parser capable of creating ASTs of compilation units in project
 */
protected ASTParser createParser(IJavaProject project) {
	ASTParser result= ASTParser.newParser(ASTProvider.SHARED_AST_LEVEL);
	result.setResolveBindings(true);
	result.setProject(project);

	return result;
}